<template>
	<view>
		<uv-navbar title="订单确认" placeholder :autoBack="true"></uv-navbar>
		<view class="p-32">
			<view class="main-bg-color p-x-28 p-y-32 m-b-26 flex">
				<u-image :src="detail.image" width="192rpx" height="192rpx" radius="12rpx" />
				<view class="m-l-20 w100">
					<view class="flex-bet-ali font-28">
						<view class="text-666">作品名称：</view>
						<view>{{ detail.product_name }}</view>
					</view>
					<u-line length="100%" color="#f5f5f5" margin="16rpx 0 25rpx"></u-line>
					<view class="flex-ali text-main font-26 font-weight-middle" @click="tool.jump_red('/packageDiy/customized/customized?diy_id=' + detail.id)">
						编辑修改
						<u-icon name="edit-pen" size="40rpx" color="#830102"></u-icon>
					</view>
					<view class="flex-bet-ali m-t-23">
						<view class="font-26 font-weight-middle">购买数量</view>
						<u-number-box v-model="detail.number" :min="1" integer />
					</view>
				</view>
			</view>
			<!-- <view class="flex-bet-ali p-28 m-y-26" style="background-color: #fff2f2">
			生成分享卡片，将设计创意分享给朋友。
			<dy-button width="144rpx" height="56rpx" openType="share" btn_bg="#830102">
				<u-icon name="share-square" size="38rpx" color="#fff" label="分享" labelSize="26rpx" labelColor="#fff"></u-icon>
			</dy-button>
		</view> -->
			<view class="address p-x-26 p-y-32" v-if="addressData?.name">
				<view class="flex aling-ali">
					<view>
						<uv-image width="38rpx" height="38rpx" :src="ASSETSURL + 'positioning.png'"></uv-image>
					</view>
					<view class="font-28 m-l-10">
						{{ addressData?.name }}
					</view>
					<view class="font-24 text-greey m-l-24">
						{{ addressData?.phone }}
					</view>
					<view class="iconDeit" @click="route('pagesA/pages/address/address', { select: true })">
						<uv-image width="40rpx" height="40rpx" :src="ASSETSURL + 'edit.png'"></uv-image>
					</view>
				</view>
				<view class="font-32 font-weight-bold m-t-22">
					{{ addressData?.province + addressData?.city + addressData?.district + addressData?.detail }}
				</view>
			</view>
			<view class="address p-x-26 p-y-32" v-else>
				<view class="flex aling-ali">
					<view>
						<uv-image width="38rpx" height="38rpx" :src="ASSETSURL + 'positioning.png'"></uv-image>
					</view>
					<view class="font-28 m-l-10">请选择地址</view>
					<view class="iconDeit" @click="route('pagesA/pages/address/address', { select: true })">
						<uv-image width="40rpx" height="40rpx" :src="ASSETSURL + 'edit.png'"></uv-image>
					</view>
				</view>
			</view>
			<view class="main-bg-color p-x-28 p-y-32 m-y-26">
				<view class="title font-30 font-weight-middle">定制尺寸</view>
				<view class="p-28 m-t-24" style="background-color: #f6f6f6; border-radius: 12rpx">
					<view class="flex-bet font-26">
						<view>实际尺寸：</view>
						<view>{{ detail.reality_size }}cm</view>
					</view>
				</view>
				<view class="title font-30 font-weight-middle m-t-40">材料信息</view>
				<view class="flex main-bg-color p-b-10 p-x-2 m-t-24">
					<view class="font-28 flex-4">名称</view>
					<view class="font-28 flex-2 text-center">单价</view>
					<view class="font-28 flex-1 text-center">数量</view>
					<view class="font-28 flex-2 text-center">小计</view>
				</view>
				<view class="p-y-14" style="background-color: #efefef; border-radius: 12rpx">
					<view class="flex p-y-14 p-x-28" v-for="(item, index) in detail.materials" :key="index">
						<view class="font-26 flex-4">{{ item.product_name }}</view>
						<view class="font-26 flex-2 text-greey text-center">￥{{ item.price / 100 }}</view>
						<view class="font-26 flex-1 text-greey text-center">{{ item.number }}</view>
						<view class="font-26 flex-2 text-center text-main">￥{{ item.total_price / 100 }}</view>
					</view>
				</view>
			</view>

			<view class="main-bg-color p-x-28 p-y-32 m-b-26" v-if="detail.configuration">
				<view class="title font-28 font-weight-middle">制作方式</view>
				<uv-radio-group v-model="radiovalue">
					<view
						class="p-28 m-t-24 w100"
						@click="radiovalue = detail.configuration.price / 100"
						:style="
							radiovalue === detail.configuration.price / 100
								? 'background-color: #f6f6f6; border-radius: 12rpx;border: 2rpx solid #840202;'
								: 'background-color: #f6f6f6; border-radius: 12rpx;'
						"
					>
						<view class="flex-bet-ali">
							<view class="font-28 font-weight-middle">成品发货</view>
							<uv-radio
								shape="square"
								:name="detail.configuration.price / 100"
								iconColor="#830102"
								:customStyle="{ width: '38rpx', height: '38rpx', borderRadius: '2rpx' }"
							></uv-radio>
						</view>
						<view class="flex-bet-ali m-t-12">
							<view class="font-24 text-greey">(由我们帮您穿好心意手串)</view>
							<view class="font-26" v-if="detail.configuration.status == 1">
								限时免费
								<text class="text-greey font-26" style="text-decoration-line: line-through">￥{{ (detail.configuration.price / 100).toFixed(2) }}</text>
							</view>
							<text v-else class="font-26 text-main">￥{{ detail.configuration.price / 100 }}</text>
						</view>
					</view>
					<view
						class="p-28 m-t-24 w100"
						@click="radiovalue = 0"
						:style="
							radiovalue === 0 ? 'background-color: #f6f6f6; border-radius: 12rpx;border: 2rpx solid #840202;' : 'background-color: #f6f6f6; border-radius: 12rpx;'
						"
					>
						<view class="flex-bet-ali">
							<view class="font-28 font-weight-middle">材料发货</view>
							<uv-radio shape="square" :name="0" iconColor="#830102" :customStyle="{ width: '38rpx', height: '38rpx' }"></uv-radio>
						</view>
						<view class="flex-bet-ali m-t-12">
							<view class="font-24 text-greey">(由您自己串好称心手串)</view>
							<view class="font-24 text-greey">免费</view>
						</view>
					</view>
				</uv-radio-group>
			</view>
			<view class="discountCoupons m-y-24 p-26">
				<view class="coupons font-30 position-relative font-weight-middle p-l-30">选择优惠券</view>
				<view
					class="discount p-y-28 p-x-26 flex align-ali justify-bet m-t-24"
					@click="
						route('pagesA/pages/myDesign/coupon', {
							select: true,
							diyId: JSON.stringify(subtotal.idList),
							morenyNumber: subtotal.price * 100 * (detail.number || 1),
							current: 1
						})
					"
				>
					<view class="font-28">优惠券</view>
					<view class="flex align-ali">
						<view class="font-30 m-r-10 text-840202">
							{{ couponData?.name || '请选择优惠劵' }}
						</view>
						<view v-if="couponData" class="m-t-6 m-l-16 m-r-16" @click.stop="couponData = null">
							<uv-icon name="close" size="20" color="#CACACA"></uv-icon>
						</view>
						<view class="m-t-6">
							<uv-icon name="arrow-right" size="20" color="#CACACA"></uv-icon>
						</view>
					</view>
				</view>
			</view>
			<view class="main-bg-color p-x-28 p-y-32 m-b-30">
				<view class="title font-30 font-weight-middle m-b-12">订单信息</view>
				<view class="flex-bet m-t-30">
					<text class="text-greey font-28">材料小计</text>
					<text class="font-28">￥{{ subtotal.price }}</text>
				</view>
				<view class="flex m-t-30 justify-bet align-ali">
					<view class="font-28 text-greey">制作费</view>
					<view class="font-28">￥{{ radiovalue > 0 && detail.configuration.status == 0 ? (radiovalue * (detail.number || 1)).toFixed(2) : '0.00' }}</view>
				</view>
				<view class="flex m-t-30 justify-bet align-ali">
					<view class="font-28 text-greey">件数</view>
					<view class="font-28">{{ detail.number || 1 }}件</view>
				</view>
				<view class="flex m-t-30 justify-bet align-ali">
					<view class="font-28 text-greey">运费</view>
					<view class="font-28">￥{{ tfreight?.price / 100 || '0.00' }}</view>
				</view>
				<view class="flex m-t-30 justify-bet align-ali">
					<view class="font-28 text-greey">优惠券</view>
					<view class="font-28">￥{{ couponData?.amount / 100 || 0 }}</view>
				</view>
				<view class="flex-bet m-t-30">
					<text class="text-greey font-28">合计</text>
					<text class="font-28 text-main font-weight-bold">￥{{ totalPrice }}</text>
				</view>
			</view>
			<view class="main-bg-color m-b-26 p-x-24 p-y-30">
				<up-collapse :border="false">
					<block v-for="(item, index) in msgList" :key="index">
						<up-collapse-item :name="item.name" :isLink="false">
							<template #title>
								<view class="font-32">{{ item.name }}</view>
							</template>
							<up-parse :content="item.content"></up-parse>
						</up-collapse-item>
						<u-line v-if="index != msgList.length - 1" length="100%" color="#D9D9D9" margin="24rpx 0"></u-line>
					</block>
				</up-collapse>
			</view>

			<view class="m-y-32">
				<dy-button btn_bg="#830102" @click="confirmOrder"><text class="font-36 font-weight-middle text-white">确认下单</text></dy-button>
			</view>
			<view class="m-b-32">
				<dy-button btn_bg="#999" plain @click="getCartBtn"><text class="font-32">添加购物车</text></dy-button>
			</view>
		</view>
	</view>
</template>

<script setup>
import { computed, ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { CustomizeCenterApi, LoginCenterApi } from '../../api/serves';
import { useCounter } from '@/mixins/userHooks';
import { getAddressDefault, getFreighttemplate, payOrder, getConfiguration, addCart, createOrder, getBaseInfo } from '@/api/api';
const { tool } = useCounter();
import route from '@/uni_modules/uv-ui-tools/libs/util/route.js';
const detail = ref({});
const tfreight = ref({});
const addressData = ref(null); //地址信息
const couponData = ref(null); //优惠劵信息
const radiovalue = ref(0);
const quantity = ref(1);
const diyId = ref([]); //AIYID
onLoad((options) => {
	getDetail(options.id);
	getAddressDefaults();
	get_configuration();
});
onShow(() => {
	uni.$once('getAddress', (res) => {
		addressData.value = res;
		getFreight();
	});
	uni.$once('getCoupon', (res) => {
		console.log(res, '-----');
		couponData.value = res;
	});
});
const msgList = ref([]);
const get_configuration = async () => {
	let { data } = await getBaseInfo();

	msgList.value = [
		{ name: '【运输说明】', content: data.find((item) => item.type == 12)?.content || '' },
		{ name: '【退换说明】', content: data.find((item) => item.type == 9)?.content || '' },
		{ name: '【保养说明】', content: data.find((item) => item.type == 7)?.content || '' },
		{ name: '【其它说明】', content: data.find((item) => item.type == 13)?.content || '' }
	];
};
//确认下单
const confirmOrder = () => {
	if (!addressData.value) {
		uni.showToast({
			title: '请选择地址',
			icon: 'none'
		});
		return;
	}
	createOrder({
		buy_mode: 1,
		add_type: 2,
		product_id: detail.value.id,
		number: detail.value.number || 1
	}).then((res) => {
		if (res.code == 1) {
			// 单个商品下单
			let data = {
				order_id: res.data.order_id,
				address_id: addressData.value.id,
				user_coupon_id: couponData.value?.id,
				is_making_fee: radiovalue.value > 0 && detail.value.configuration.status == 0 ? 1 : 0,
				is_making_number: detail.value.number
			};
			payOrder(data).then((res) => {
				if (res.code == 1) {
					tool.requestPayment(res.data.js_config).then((res2) => {
						route(`/pagesA/pages/originality/orderDetails`, { orderSn: res.data.order_sn });
					});
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					});
				}
			});
		} else {
			uni.showToast({ title: res.msg, icon: 'none' });
		}
	});
};

// 加入购物车
const getCartBtn = () => {
	let data = {
		add_type: 2,
		diy_id: detail.value.id,
		cart_num: detail.value.number || 1,
		is_making_fee: radiovalue.value > 0 && detail.value.configuration.status == 0 ? 1 : 0
	};
	addCart(data).then((res) => {
		console.log(res, '加入购物车');
		// 加入购物车
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
		setTimeout(() => {
			route('packageOrder/shopCar/shopCar');
		}, 1000);
	});
};
const subtotal = computed(() => {
	let num = 0;
	let arr = [];
	let list = detail?.value.materials || [];
	list.forEach((item) => {
		num += item.total_price;
		if (item.unique) arr.push({ unique: item.unique, quantity: item.number });
	});
	console.log(num, 'arr');
	return { price: num / 100, idList: arr };
});
const totalPrice = computed(() => {
	let amount = couponData.value?.amount || 0; // 优惠券金额（分）
	let price = tfreight.value.price || 0; // 运费（分）
	let number = detail.value.number || 1;
	let makingFee = detail.value?.configuration?.status == 1 ? 0 : radiovalue.value * 100 * number; // 制作费（分）
	let goodsTotal = subtotal?.value.price * 100 * number + makingFee; // 商品+制作费（分）
	let afterCoupon = Math.max(goodsTotal - amount, 1); // 优惠后最低1分
	let num = (afterCoupon + price) / 100; // 加上运费
	return num.toFixed(2);
});
//获取运费
const getFreight = async () => {
	console.log('获取运费1');
	if (addressData.value) {
		await getFreighttemplate({ province: addressData.value.province }).then((res) => {
			console.log(res, '获取运费2');
			tfreight.value = res.data;
		});
	}
};
//获取默认地址
const getAddressDefaults = async () => {
	await getAddressDefault().then((res) => {
		console.log(res, '获取默认地址');
		addressData.value = res.data;
		getFreight();
	});
};

const getDetail = async (id) => {
	let { code, data, msg } = await CustomizeCenterApi.get_fabrication({ id });
	if (code != 1) return tool.alert(msg);
	data.materials = [data.line, ...data.materials];
	detail.value = data;
};
</script>
<style>
page {
	background: #f6f6f6;
}

.uv-radio__icon-wrap {
	width: 38rpx !important;
	height: 38rpx !important;
	border-color: #830102 !important;
	border-radius: 6rpx !important;
	background-color: transparent !important;
}
</style>
<style lang="scss" scoped>
.title {
	padding: 0 30rpx;
	position: relative;

	&::before {
		content: ' ';
		width: 14rpx;
		height: 14rpx;
		background: #830102;
		position: absolute;
		border-radius: 50%;
		left: 0rpx;
		top: 16rpx;
	}
}

.discountCoupons {
	width: 686rpx;
	// height: 216rpx;
	background: #fff;
	border-radius: 12rpx;

	.coupons {
		&::after {
			content: '';
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 14rpx;
			height: 14rpx;
			border-radius: 50%;
			background: #830102;
		}
	}

	.discount {
		width: 634rpx;
		height: 96rpx;
		background: #f6f6f6;
		border-radius: 12rpx;
	}
}

.address {
	width: 686rpx;
	// height: 178rpx;
	background: #fff;
	border-radius: 12rpx;

	.iconDeit {
		margin-left: auto;
	}
}

::v-deep .u-cell__body {
	padding: 0rem !important;
}

::v-deep .u-collapse-item__content__text {
	padding: 16rpx 8rpx 0 !important;
}
</style>
